package org.yzh.web.business.kafka.producer;

import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class Producer4Kafka {
    /**
     * topic 的名称
     */
    public final static String TOPIC_NAME = "gwdTest";
    public final static String kafka_key = "key_1";

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;


    public void test() {
        //发送功能就一行代码~
        kafkaTemplate.send(TOPIC_NAME, kafka_key, "gwd test message send~");
    }


    /**
     * 异步发送消息方法
     *
     * @param topic
     * @param message
     */
    public void sendAsync(String topic, String message) {
        kafkaTemplate.send(topic, message);
    }

    /**
     * 同步发送消息方法
     *
     * @param topic
     * @param message
     * @throws Exception
     */
    public void sendSync(String topic, String message) throws Exception {
        kafkaTemplate.send(topic, message).get();
    }

//    @Scheduled(cron = "0/2 * * * * ?")
//    public void timer() {
//        SimpleDateFormat format = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
//        Date now = new Date();
//        sendAsync(TOPIC_NAME, format.format(now).toString());
//        System.out.println("=============================定时 push to kafka =======================");
//    }
}
